//
//  HDCFOpenAccountVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/4.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFOpenAccountVc.h"
#import "HDCFOpenAccountCell.h"
#import "SVProgressHUD.h"
#import "HDCFBankListVc.h"
#import "OpenAccountFooter.h"
#import "OpenAccountFooter.h"
#import "HDCFcommenQuestionVc.h"

@interface HDCFOpenAccountVc ()<UITextFieldDelegate, HDCFBankListVcDelegate>

@property (nonatomic, strong) NSArray *imageAry;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSMutableArray *placeHoldArray;
@property (nonatomic, strong) NSArray *modelArray;

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *idCardNum;
@property (nonatomic, copy) NSString *bankcode;
@property (nonatomic, copy) NSString *bankNumber;
@property (nonatomic, copy) NSString *telHp;
@property (nonatomic, copy) NSString *otp;
@property (nonatomic, copy) NSString *token;
@property (nonatomic, copy) NSString *tradeCode;
@property (nonatomic, weak) UIView *clearHudView;

//权益须知，服务协议是否同意
@property (nonatomic, assign) BOOL isOpenAvlable;
//诚信记录
@property (nonatomic, assign) BOOL isOpenAvaliableTwo;
//是否中国税收居民
@property (nonatomic, assign) BOOL isOpenAvaliableThree;

@end

@implementation HDCFOpenAccountVc


- (NSMutableArray *)placeHoldArray{
    if (!_placeHoldArray) {
        self.placeHoldArray = [NSMutableArray arrayWithObjects:@"请输入姓名(必填)", @"请输入身份证号(必填)", @"请选择银行(必填)", @"请输入银行卡号(必填)", @"请输入交易密码(必填)", @"请输入银行预留手机(必填)", @"请输入验证码(必填)", nil];
    }
    return _placeHoldArray;
}

- (NSArray *)imageAry{
    if (!_imageAry) {
        self.imageAry = [NSArray arrayWithObjects:@"icon_name", @"iocn_shenfenzheng", @"icon_xuanzeyinhang", @"icon_ka2", @"icon_jiaoyimima", @"icon_yuliushouji", @"icon_yanzhengma", nil];
    }
    return _imageAry;
}

- (NSArray *)titleArray{
    if (!_titleArray) {
        self.titleArray = [NSArray arrayWithObjects:@"姓名(必填)", @"身份证号(必填)", @"银行卡号(必填)", @"交易密码(必填)", @"银行预留手机号(必填)", @"短信验证码(必填)", nil];
    }
    return _titleArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationItem setTitle:@"申请开户"];
    self.otp = @"000000";
    self.view.backgroundColor = ZKcolor(245, 245, 245);
    self.tableView.tableFooterView = [self setTabelFooter];
    self.tableView.separatorColor = ZKcolor(245, 245, 245);
    self.tableView.frame = CGRectMake(0, 0, screenWidth, screenHeight - 49 - KNavHeight);
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:@"提交申请" forState:UIControlStateNormal];
    [btn setBackgroundColor:ZKcolor(182, 27, 36)];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, screenHeight - 49 - KNavHeight, screenWidth, 49);
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
}

- (UIView *)setTabelFooter{
    OpenAccountFooter *footer = [OpenAccountFooter OpenAccountFooter];
    footer.frame = CGRectMake(0, 0, screenWidth, 250);
    footer.isSelectBtn.selected = YES;
    footer.fourBtn.selected = YES;
    footer.fiveBtn.selected = YES;
    _isOpenAvlable = YES;
    _isOpenAvaliableTwo = YES;
    _isOpenAvaliableThree = YES;
    [footer.isSelectBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer.oneBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer.twoBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer.threeBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer.fourBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer.fiveBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    UIButton *btnTwoYF = [[UIButton alloc] init];
//    btnTwoYF.frame = CGRectMake(0, CGRectGetMaxY(middleTable.frame), screenWidth, 50);
    [footer.threeBtn setBackgroundColor:ZKcolor(245, 245, 245)];
    NSString *strleft = @"基金销售服务由奕丰金融提供\n-基金有风险 投资需谨慎-";
    NSMutableAttributedString *attrStrT = [[NSMutableAttributedString alloc] initWithString:strleft];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:[UIColor lightGrayColor]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:12]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:14]
                     range:NSMakeRange(7, 4)];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:ZKcolor(33, 33, 33)
                     range:NSMakeRange(7, 4)];
    [footer.threeBtn setAttributedTitle:attrStrT forState:UIControlStateNormal];
    [footer.threeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [footer.threeBtn.titleLabel setTextAlignment:NSTextAlignmentCenter];
    footer.threeBtn.titleLabel.lineBreakMode = 0;
    return footer;
}

- (void)footerBtnClick:(UIButton *)btn{
    if (btn.tag == 1) {
        btn.selected = !btn.selected;
        if (btn.selected == YES) {
            _isOpenAvlable = YES;
        }else{
            _isOpenAvlable = NO;
        }
    }else if (btn.tag == 2){
        HDCFcommenQuestionVc *vc = [[HDCFcommenQuestionVc alloc] init];
        vc.typeInteger = 1;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (btn.tag == 3){
        HDCFcommenQuestionVc *vc = [[HDCFcommenQuestionVc alloc] init];
        vc.typeInteger = 2;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (btn.tag == 4){
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIView *view = [[UIView alloc] init];
        self.clearHudView = view;
        view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
        r5.numberOfTapsRequired = 1;
        [view addGestureRecognizer:r5];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(30, (screenHeight - (screenWidth - 60) * 900.0 / 500.0) / 2, screenWidth - 60, (screenWidth - 60) * 900.0 / 500.0);
        imageView.image = [UIImage imageNamed:@"661511947049_.pic_hd.jpg"];
        [view addSubview:imageView];
        view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
        [window addSubview:view];

    }else if (btn.tag == 5){
        btn.selected = !btn.selected;
        if (btn.selected == YES) {
            _isOpenAvaliableTwo = YES;
        }else{
            _isOpenAvaliableTwo = NO;
        }
    }else if (btn.tag == 6){
        btn.selected = !btn.selected;
        if (btn.selected == YES) {
            _isOpenAvaliableThree = YES;
        }else{
            _isOpenAvaliableThree = NO;
        }
    }
}

- (void)viewHit{
    [self.clearHudView removeFromSuperview];
}

- (void)confirm{
    
    if (_isOpenAvlable == NO) {
        [SVProgressHUD showInfoWithStatus:@"请先阅读《投资人权益须知》、《奕丰金融平台服务协议》"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (_isOpenAvaliableTwo == NO) {
        [SVProgressHUD showInfoWithStatus:@"请先确认无不良诚信记录和交易账户的实际控制投资者为您本人"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (_isOpenAvaliableThree == NO) {
        [SVProgressHUD showInfoWithStatus:@"请先确认您的税收情况"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (self.name.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入姓名"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.idCardNum.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入身份证号"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.bankcode.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请选择银行"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.bankNumber.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入银行卡号"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (self.tradeCode.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入交易密码"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (self.telHp.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入银行预留手机号"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.otp.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入验证码"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    
    
    [SVProgressHUD show];
    NSMutableDictionary *dictOne = [NSMutableDictionary dictionary];
    dictOne[@"bankCode"] = self.bankcode;
    dictOne[@"idName"] = self.name;
    dictOne[@"idNumber"] = self.idCardNum;
    dictOne[@"idType"] = @"0";
    dictOne[@"bankNumber"] = self.bankNumber;
    dictOne[@"telHp"] = self.telHp;
    dictOne[@"otp"] = self.otp;
    dictOne[@"token"] = self.token;
    if (self.tradeCode.length > 0) {
        dictOne[@"password"] = self.tradeCode;
    }
    NSString *jsonString = [self dictionaryToJson:dictOne];
    
    NSDictionary *paramet = @{
                           KparametTwo:@"/public/investor/register-investor",
                           KparametOne:jsonString
                           };
    [HttpRequest sendPostRequestWithURL:nil WithParamets:paramet WithJsonString:nil success:^(id result) {
        if ([result[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showInfoWithStatus:@"开户成功"];
            [SVProgressHUD dismissWithDelay:1.0];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setValue:@"1" forKey:@"OpenStatue"];
            NSDictionary*dataDic=[result objectForKey:@"data"];
           NSString*investorPayId=[dataDic objectForKey:@"investorPayId"];
            if (investorPayId) {
                [user setObject:investorPayId forKey:@"investorPayId"];
            }
            [user synchronize];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
                if ([self.delegate respondsToSelector:@selector(openAccountSucess)]) {
                    [self.delegate openAccountSucess];
                }
            });
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
    
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    NSString *jsonTemp2 = [jsonTemp stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    
    return jsonTemp;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellid";
    HDCFOpenAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [HDCFOpenAccountCell HDCFOpenAccountCell];
    }
    NSString *imgName = self.imageAry[indexPath.row];
    NSString *placeH = self.placeHoldArray[indexPath.row];
    
    cell.textTf.placeholder = placeH;
    cell.textTf.delegate = self;
    cell.textTf.tag = 10 + indexPath.row;
    cell.imgView.image = [UIImage imageNamed:imgName];
    
    [cell.textTf addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    
    if (indexPath.row == 6) {
        [cell.sendCodeBtn setBackgroundImage:[UIImage imageNamed:@"button_yanzhengma"] forState:UIControlStateNormal];
        [cell.sendCodeBtn addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
    }else{
        cell.btnWidth.constant = 0;
    }
    if (indexPath.row == 2) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)sendCode{
    if (self.name.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入姓名"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.idCardNum.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入身份证号"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.bankcode.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请选择银行"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (self.bankNumber.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入银行卡号"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (self.tradeCode.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入交易密码"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (self.tradeCode.length < 6 || self.tradeCode.length > 20) {
        [SVProgressHUD showInfoWithStatus:@"密码长度不正确"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    if (self.telHp.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入银行预留手机号"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    [SVProgressHUD show];
    NSMutableDictionary *dictOne = [NSMutableDictionary dictionary];
    dictOne[@"bankCode"] = self.bankcode;
    dictOne[@"idName"] = self.name;
    dictOne[@"idNumber"] = self.idCardNum;
    dictOne[@"idType"] = @"0";
    dictOne[@"bankNumber"] = self.bankNumber;
    dictOne[@"telephoneNumber"] = self.telHp;
    
    NSString *jsonString = [self dictionaryToJson:dictOne];
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/investor/send-otp",
                              KparametOne:jsonString
                              };
    [HttpRequest sendPostRequestWithURL:nil WithParamets:paramet WithJsonString:nil success:^(id result) {
        if ([result[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showSuccessWithStatus:@"发送成功"];
            [SVProgressHUD  dismissWithDelay:1.0];
            
            self.token = result[@"data"];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD  dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD  dismissWithDelay:1.0];
    }];
}

- (void)textChange:(UITextField *)textField{
    if (textField.tag == 10) {
        self.name = textField.text;
    }else if (textField.tag == 11){
        self.idCardNum = textField.text;
    }else if (textField.tag == 13){
        self.bankNumber = textField.text;
    }else if (textField.tag == 14){
        self.tradeCode = textField.text;
    }else if (textField.tag == 15){
        self.telHp = textField.text;
    }else{
        self.otp = textField.text;
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField.tag == 12) {
        HDCFBankListVc *vc = [[HDCFBankListVc alloc] init];
        vc.delegate = self;
        vc.textField = textField;
        [self.navigationController pushViewController:vc animated:YES];
        return NO;
    }else{
        return YES;
    }
}


- (void)returnWithBankDict:(NSDictionary *)dict withTextField:(UITextField *)textField{
    textField.text = dict[@"bankName"];
    self.bankcode = dict[@"bankCode"];
}



@end
